<?php
namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\popularize\Popularize as PopularizeModel;
use think\exception\DbException;
use think\Request;
use think\Response;
use think\Validate;

/**
 * 自媒体推广接口
 */
class Popularize extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }


    /**
     * 获取自媒体推广列表（支持多条件筛选）
     * @param Request $request
     * @return Response
     * @throws DbException
     */
    public function list(Request $request): \think\Response
    {
        // 获取请求参数
        $params = $request->param();
        $page = $request->param('page', 1, 'intval');
        $limit = $request->param('limit', 10, 'intval');

        // 构建查询条件
        $where = [];

        // 基础筛选条件
        if (!empty($params['name'])) {
            $where[] = ['name', 'like', "%{$params['name']}%"];
        }
        if (!empty($params['area'])) {
            $where[] = ['area', '=', $params['area']];
        }
        if (!empty($params['channel_type'])) {
            $where[] = ['channel_type', '=', $params['channel_type']];
        }
        if (!empty($params['news_source'])) {
            $where[] = ['news_source', '=', $params['news_source']];
        }
        if (!empty($params['status'])) {
            $where[] = ['status', '=', $params['status']];
        }

        // 价格范围筛选
        if (!empty($params['min_cost_price'])) {
            $where[] = ['cost_price', '>=', $params['min_cost_price']];
        }
        if (!empty($params['max_cost_price'])) {
            $where[] = ['cost_price', '<=', $params['max_cost_price']];
        }

        // 出稿量范围筛选
        if (!empty($params['min_publish_num'])) {
            $where[] = ['publish_num', '>=', $params['min_publish_num']];
        }
        if (!empty($params['max_publish_num'])) {
            $where[] = ['publish_num', '<=', $params['max_publish_num']];
        }

        // 排序处理
        $order = 'id DESC';
        if (!empty($params['sort_field']) && !empty($params['sort_order'])) {
            $order = "{$params['sort_field']} {$params['sort_order']}";
        }

        // 查询数据
        $list = PopularizeModel::where($where)
            ->order($order)
            ->paginate([
                'list_rows' => $limit,
                'page' => $page,
            ]);

        // 获取所有可用的筛选选项（用于前端筛选控件）
        $filterOptions = [
            'area' => (new PopularizeModel)->distinct(true)->column('area'),
            'channel_type' => (new PopularizeModel)->distinct(true)->column('channel_type'),
            'news_source' => (new PopularizeModel)->distinct(true)->column('news_source'),
            'status_options' => ['1' => '通过', '2' => '待审核', '3' => '暂停显示']
        ];

        return json([
            'code' => 200,
            'msg' => 'success',
            'data' => [
                'list' => $list->items(),
                'total' => $list->total(),
                'current_page' => $list->currentPage(),
                'last_page' => $list->lastPage(),
                'filter_options' => $filterOptions
            ]
        ]);
    }

    /**
     * 获取自媒体推广列表
     * @param Request $request
     * @return \think\Response
     */
    public function index(Request $request)
    {
        // 获取请求参数
        $page = $request->param('page', 1, 'intval');
        $limit = $request->param('limit', 10, 'intval');

        $where['author'] = $this->auth->id;

        // 查询数据
        $list = PopularizeModel::where($where)
            ->order('id', 'desc')
            ->paginate($limit, false, ['page' => $page]);

        return json([
            'code' => 200,
            'msg' => 'success',
            'data' => $list->items(),
            'total' => $list->total(),
            'current_page' => $list->currentPage(),
            'last_page' => $list->lastPage()
        ]);
    }

    /**
     * 统一保存接口（新增或更新）
     * @param Request $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        // 获取所有输入数据
        $data = $request->post();

        // 验证数据
        $validate = Validate::make([
            'name' => 'require|max:255',
            'vip_price' => 'max:255',
            'publish_num' => 'number',
            'cost_price' => 'float',
            'push_price' => 'float',
        ], [
            'name.require' => '媒体名称不能为空',
            'name.max' => '媒体名称不能超过255个字符',
            'vip_price.max' => 'VIP价格不能超过255个字符',
            'publish_num.number' => '出稿量必须是数字',
            'cost_price.float' => '成本价格必须是数字',
            'push_price.float' => '发稿速度必须是数字',
        ]);

        if (!$validate->check($data)) {
            return json([
                'code' => 400,
                'msg' => $validate->getError(),
                'data' => null
            ]);
        }

        // 获取当前登录用户ID并写入author字段
        $data['author'] = $this->auth->id;
        // 判断是新增还是更新
        if (empty($data['id'])) {
            // 新增操作
            $model = new PopularizeModel;
            $result = $model->save($data);
            $message = '新增成功';
        } else {
            // 更新操作
            $model = PopularizeModel::find($data['id']);
            if (!$model) {
                return json([
                    'code' => 404,
                    'msg' => '记录不存在',
                    'data' => null
                ]);
            }
            $result = $model->save($data);
            $message = '更新成功';
        }

        // 设置状态
        $data['status'] = 1;

        if ($result) {
            return json([
                'code' => 200,
                'msg' => $message,
                'data' => $model->id
            ]);
        } else {
            return json([
                'code' => 500,
                'msg' => '操作失败',
                'data' => null
            ]);
        }
    }
}